#include "header.h"

void *msgLifeTimer(void *ptr)
{
	printf("MSGLIFETIMER THREAD CREATED\n");
	while(1)
	{
		if(shutdownFlag == true || joinToTheNetworkFlag == true)
		{
			printf("MsgLifeTimer Thread EXIT due to Shutdown\n");
			
			pthread_exit(NULL);
		}
		sleep(1);
		map<string, int>::iterator it1;
		map<string, int>::iterator it2;
		//map<string, int>::iterator temp;

		pthread_mutex_lock(&UoidMap);												//APPLY LOCK

		//printf("Decrementing Msg Life Time...\n");
		map<string,int>tempUoidMessageLifeTimeMap = node.getUoidMessageLifeTime();
		map<string,int>tempUoidSocketDescripter = node.getUoidSocketDescripter();
		
		//printf("SIZE -----> %d\n",tempUoidMessageLifeTimeMap.size());

		for(it1 = tempUoidMessageLifeTimeMap.begin(), it2 = tempUoidSocketDescripter.begin(); it1!= tempUoidMessageLifeTimeMap.end();it1++,it2++)
		{
			//cout<<"Before Decrementing Uoid="<<(*it1).first<<"     MsgLifeTime="<<(*it1).second<<endl;
			int msgLifeTime = (*it1).second - 1;										//decrement the timer by one
			if(msgLifeTime == 0)
			{
				tempUoidMessageLifeTimeMap.erase(it1);
				tempUoidSocketDescripter.erase(it2);
				printf("Msg expired\n");
			}
			else
			{
				it1 = tempUoidMessageLifeTimeMap.find((*it1).first);
				it1->second = msgLifeTime;
				//cout<<"After Decrementing Uoid="<<(*it1).first<<"     MsgLifeTime="<<(*it1).second<<endl;
			}
		}
		node.setUoidMessageLifeTime(tempUoidMessageLifeTimeMap);
		node.setUoidSocketDescripter(tempUoidSocketDescripter);

		pthread_mutex_unlock(&UoidMap);												//RELEASE LOCK

	}
}
